﻿using Comm.Model.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Comm.Utility;

namespace Comm.Web.View
{
    /// <summary>
    /// Login 的摘要说明
    /// </summary>
    public class Login : IHttpHandler,System.Web.SessionState.IRequiresSessionState
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public string Message { get; set; }
        HttpContext context = null;
        private BLL.UserServices _userService = new BLL.UserServices();

        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            //HttpCookie cookies = context.Request.Cookies["USER_COOKIE"];
            //if (cookies != null) {
            //    //如果Cookie不为空，则将Cookie里面的用户名和密码读取出来赋值给前台的文本框。
            //    context.Request.Form["ULoginName"] = cookies["UserName"];
            //    context.Request.Form["UPwd"] = cookies["UserPassword"];
            //    context.Request.Form["chkAlways"] = "true";
            //}
            string strType = context.Request.Params["t"];
            switch (strType)
            {
                case "l"://登录
                    Login1();
                    break;
                case "2"://登录
                    Regriter();
                    break;
            }
        }

        #region 1. 登录验证+void Login1()
        private void Login1()
        {
            // 接收参数
            Username = context.Request.Form["ULoginName"];
            Password = context.Request.Form["UPwd"];
            var vcode = context.Request.Form["UCode"];
            var chkAlways = context.Request.Form["chkAlways"] != null;
            // 参数校验
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                AjaxMsgHelper.AjaxMsg("err", "用户名或密码错误~~！");
            }

            //校验验证码
            var session = context.Session["code"];
            if (session == null || vcode != session.ToString())
            {
                AjaxMsgHelper.AjaxMsg("302", "验证码错误~~！");
                context.Response.End();
            }

            Model.Users user;
            LoginResult res = _userService.CookieLogin(Username, Password, out user);
            switch (res)
            {
                case LoginResult.用户名不存在:
                case LoginResult.密码错误:
                    AjaxMsgHelper.AjaxMsg("err", "用户名或密码错误~~！");
                    return;
                case LoginResult.用户已被冻结:
                    Message = "用户状态异常！";
                    AjaxMsgHelper.AjaxMsg("err", "用户状态异常~~！");
                    return;
                case LoginResult.登录成功:
                    // 将当前用户实体放到Session中
                    context.Session["current_user"] = user;
                    try
                    {
                        //使用Cookie保存登录用户 id（安全，节约传输大小）
                        if (!string.IsNullOrEmpty(context.Request.Form["chkAlways"]))
                        {
                            //1.
                            //HttpCookie cookie = new HttpCookie("current_user", user.uId.ToString());
                            //cookie.Expires = DateTime.Now.AddMinutes(60);
                            //cookie.Path = "/manage/";
                            //context.Response.Cookies.Add(cookie);

                            // // 2.处理记住我
                            // //HttpCookie c1 = new HttpCookie("uLoginName");
                            // //c1.Value = user.uLoginName;
                            // //HttpCookie c2 = new HttpCookie("uPwd");
                            // //c2.Value = user.uPwd;
                            // //context.Response.Cookies.Add(c1);
                            // //context.Response.Cookies.Add(c2);
                            //CookieHelper.Set("uLoginName", Username, DateTime.Now.AddDays(7));
                            //CookieHelper.Set("uPwd", Password, DateTime.Now.AddDays(7));

                            //3.
                            HttpCookie cookie = new HttpCookie("current_user");

                            //所有的验证信息检测之后，如果用户选择的记住密码，则将用户名和密码写入Cookie里面保存起来。
                            cookie.Values.Add("UserName", Username);
                            cookie.Values.Add("UserPassword", Password);
                            cookie.Values.Add("UId", user.uId.ToString());
                            //这里是设置Cookie的过期时间，这里设置一个星期的时间，过了一个星期之后状态保持自动清空。
                            cookie.Expires = System.DateTime.Now.AddDays(7.0);
                            HttpContext.Current.Response.Cookies.Add(cookie);
                        }
                        //else {
                        //    if (cookie["USER_COOKIE"] != null) { 
                        //       //如果用户没有选择记住密码，那么立即将Cookie里面的信息情况，并且设置状态保持立即过期。
                        //         context.Response.Cookies["USER_COOKIE"].Expires = DateTime.Now;
                        //    }
                        //}

                        AjaxMsgHelper.AjaxMsg("ok", "用户登录成功~~！", null, "../View/Index.aspx");
                    }
                    catch (Exception ex)
                    {
                        AjaxMsgHelper.AjaxMsg("err", "异常：" + ex.Message);
                    }
                    break;
            }
        } 
        #endregion

        #region 2. 注册验证+void Regriter()
        private void Regriter()
        {
            // 接收参数
            Username = context.Request.Form["ULoginName"];
            Password = context.Request.Form["UPwd"];
            var vcode = context.Request.Form["UCode"];
            // 参数校验
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                AjaxMsgHelper.AjaxMsg("err", "用户名或密码错误~~！");
            }

            //校验验证码
            var session = context.Session["code"];
            if (session == null || vcode != session.ToString())
            {
                AjaxMsgHelper.AjaxMsg("302", "验证码错误~~！");
                context.Response.End();
            }

            Model.Users user;
            RegisterResult res = _userService.Register(Username, Password, out user);
            switch (res)
            {
                  case RegisterResult.用户名已存在:
                        AjaxMsgHelper.AjaxMsg("err", "用户名已存在~~！");
                         break;
                    case RegisterResult.注册成功:
                        Message = "注册成功";
                        //跳转到注册之前的页面
                        //Response.Redirect(redirect);                       
                        AjaxMsgHelper.AjaxMsg("ok", "用户注册成功~~！", null, "../html/login.html");
                        break;
                    case RegisterResult.注册失败:
                        AjaxMsgHelper.AjaxMsg("err", "注册失败~~！");
                        break;
            }
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}